package com.zyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping()
    public String tologin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session){
        String sessionCode = (String) session.getAttribute("code");
        //验证码忽略大小写
        if(!sessionCode.equalsIgnoreCase(code)){
            return "redirect:/";
        }else {
          User u=  userService.login(user);
            if(u!=null){
                StpUtil.login(u.getId());
//                return "index";
                return "redirect:/toindex";
            }else {
                return "redirect:/";
            }
        }
    }
    @RequestMapping("/captcha")
    @ResponseBody
    public String captcha(HttpSession session){
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        String code=captcha.getCode();
        session.setAttribute("code",code);
        String data= JSON.toJSONString(captcha.getImageBase64());
        return data;
    }
}
